﻿/*----------------------------------------------------------------
// Copyright (C) 2014 苏州麦迪斯顿医疗科技股份有限公司
// 文件名：UnityInstanceProvider.cs
// 文件功能描述：UnityInstanceProvider
// 创建标识：顾伟伟-2014-04-03
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;

namespace CPOE.Framework.Injection
{
    /// <summary>
    /// 一个自定义的IInstanceProvider，使用Unity容器创建服务实例，实现依赖注入和策略注入
    /// </summary>
    public class UnityInstanceProvider : IInstanceProvider
    {
        private IUnityContainer _unityContainer { get; set; }

        public UnityInstanceProvider(IUnityContainer unityContainer)
        {
            _unityContainer = unityContainer;
        }
        /// <summary>
        /// 使用Unity IoC容器创建服务实例
        /// </summary>
        /// <param name="instanceContext"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            Type serviceType = instanceContext.Host.Description.ServiceType;

            object serviceInstance = Activator.CreateInstance(serviceType);

            if (!serviceType.IsInterface && !serviceType.IsMarshalByRef)
                return serviceInstance;
            //使用Unity容器创建服务实例
            return  this._unityContainer.BuildUp(serviceType,serviceInstance);

        }

        public object GetInstance(InstanceContext instanceContext)
        {
            return GetInstance(instanceContext, null);
        }
        /// <summary>
        /// 释放服务实例
        /// </summary>
        /// <param name="instanceContext"></param>
        /// <param name="instance"></param>
        public void ReleaseInstance(InstanceContext instanceContext, object instance)
        {
            _unityContainer.Teardown(instance);
        }
    }
}
